package com.kedacom.freedomLabel.view.widget;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatDialogFragment;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.databinding.DialogKeyboardLayoutBinding;
import com.kedacom.freedomLabel.model.DialogKeyboardParams;
import com.kedacom.lego.message.LegoMessageManager;
import com.lzscale.scalelib.misclib.Misc;

import java.util.regex.Pattern;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


/**
 * 数字输入框
 *
 * @author licheng
 * @since 2020/3/9 14:55
 */
public class DialogKeyboard extends AppCompatDialogFragment {

    public static final String RESULT_MESSAGE_TYPE = "DialogKeyboard-AppCompatDialogFragment";

    private static final String NOT_NEGATIVE_INTEGER = "^[1-9]\\d*|0$";
    private static final String POSITIVE_FLOAT = "^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$";

    private FragmentActivity mActivity;

    private DialogKeyboardLayoutBinding mBinding;
    private DialogKeyboardParams mDialogKeyboardParams;
    private StringBuilder mStringBuilder = new StringBuilder();
    private Misc mMisc = Misc.newInstance();
    private View.OnClickListener mOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View child) {
            mMisc.beep();
            String inputText = child.getTag().toString();
            String dot = ".";
            int indexOfDot = mStringBuilder.indexOf(dot);
            if (inputText.equals(dot)) {
                if (mDialogKeyboardParams.type != DialogKeyboardParams.TYPE.INTEGER) {
                    if (indexOfDot == -1 && mStringBuilder.length() == 0) {
                        mStringBuilder.append("0").append(dot);
                    } else if (indexOfDot == -1) {
                        mStringBuilder.append(dot);
                    }
                }
            } else {
                mStringBuilder.append(inputText);
            }
            mBinding.container.setText(mStringBuilder);
        }
    };

    public static DialogKeyboard newInstance(@NonNull DialogKeyboardParams params) {
        DialogKeyboard dialog = new DialogKeyboard();
        dialog.setDialogKeyboardParams(params);
        return dialog;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(AppCompatDialogFragment.STYLE_NO_TITLE, 0);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mActivity = (FragmentActivity) context;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mActivity = null;
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(this, tag);
        transaction.commitAllowingStateLoss();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        mStringBuilder.delete(0, mStringBuilder.length());
        mStringBuilder = null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.dialog_keyboard_layout, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        addClickProxy(mBinding.parent);
        mBinding.title.setText(mDialogKeyboardParams.getTitle());
        mBinding.clear.setOnClickListener(v -> {
            mMisc.beep();
            mStringBuilder.delete(0, mStringBuilder.length());
            mBinding.container.setText(null);
        });
        mBinding.confirm.setOnClickListener(v -> {
            mMisc.beep();
            if (mStringBuilder.lastIndexOf(".") == mStringBuilder.length() - 1) {
                mStringBuilder.append("0");
                mBinding.container.setText(mStringBuilder);
            }
            String inputText = mBinding.container.getText().toString();
            if (mDialogKeyboardParams.type == DialogKeyboardParams.TYPE.INTEGER) {
                if (Pattern.compile(NOT_NEGATIVE_INTEGER).matcher(inputText).matches()) {
                    mDialogKeyboardParams.setResult(inputText);
                    LegoMessageManager.getInstance().sendMessage(RESULT_MESSAGE_TYPE, mDialogKeyboardParams);
                    dismiss();
                }
            } else if (mDialogKeyboardParams.type == DialogKeyboardParams.TYPE.FLOAT) {
                if (Pattern.compile(POSITIVE_FLOAT).matcher(inputText).matches()) {
                    mDialogKeyboardParams.setResult(inputText);
                    LegoMessageManager.getInstance().sendMessage(RESULT_MESSAGE_TYPE, mDialogKeyboardParams);
                    dismiss();
                }
            } else if (mDialogKeyboardParams.type == DialogKeyboardParams.TYPE.FLOAT_INTEGER) {
                mDialogKeyboardParams.setResult(inputText);
                LegoMessageManager.getInstance().sendMessage(RESULT_MESSAGE_TYPE, mDialogKeyboardParams);
                dismiss();
            }
        });
        mBinding.back.setOnClickListener(v -> {
            mMisc.beep();
            dismiss();
        });
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Window window = getDialog().getWindow();
        if (window != null) {
            window.setWindowAnimations(R.style.picker_view_scale_anim);
            DisplayMetrics dm = new DisplayMetrics();
            if (mActivity != null) {
                WindowManager windowManager = mActivity.getWindowManager();
                windowManager.getDefaultDisplay().getMetrics(dm);
                window.setGravity(Gravity.CENTER);
                window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        }
    }

    private void setDialogKeyboardParams(DialogKeyboardParams params) {
        this.mDialogKeyboardParams = params;
    }

    private void addClickProxy(View view) {
        if (view instanceof ViewGroup) {
            setViewProxy((ViewGroup) view);
        } else {
            hook(view);
        }
    }

    private void setViewProxy(ViewGroup viewGroup) {
        hook(viewGroup);
        int count = viewGroup.getChildCount();
        for (int i = 0; i < count; i++) {
            if (viewGroup.getChildAt(i) instanceof ViewGroup) {
                setViewProxy((ViewGroup) viewGroup.getChildAt(i));
            } else {
                hook(viewGroup.getChildAt(i));
            }
        }
    }

    private void hook(View view) {
        if (view.getTag() != null) {
            view.setOnClickListener(mOnClickListener);
        }
    }
}